package com.atguigu.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.product.service.CategoryBrandRelationService;
import com.atguigu.product.vo.Catalog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.product.dao.CategoryDao;
import com.atguigu.product.entity.CategoryEntity;
import com.atguigu.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

  @Resource
  CategoryBrandRelationService categoryBrandRelationService;

  @Resource
  StringRedisTemplate stringRedisTemplate;

  @Resource
  RedissonClient redisson;

  @Override
  public PageUtils queryPage(Map<String, Object> params) {
    IPage<CategoryEntity> page = this.page(
      new Query<CategoryEntity>().getPage(params),
      new QueryWrapper<CategoryEntity>()
    );
    return new PageUtils(page);
  }

  @Override
  public List<CategoryEntity> listWithTree() {
    //查出所有分类
    List<CategoryEntity> list = baseMapper.selectList(null);

    //组装成树
    //找到所有的一级分类
    List<CategoryEntity> level1Menus = list.stream().filter(categoryEntity ->
      categoryEntity.getParentCid() == 0
    ).map(menu -> {
      menu.setChildren(getChildrens(menu, list));
      return menu;
    }).sorted(Comparator.comparingInt(CategoryEntity::getSort)).collect(Collectors.toList());

    return level1Menus;
  }

  @Override
  public void removeMenuByIds(List<Long> asList) {
    //TODO 1、检查当前删除的菜单，是否被别的地方引用
    //逻辑删除
    baseMapper.deleteBatchIds(asList);
  }

  @Override
  public Long[] findCatelogPath(Long catelogId) {
    List<Long> paths = new ArrayList<>();
    List<Long> parentPath = findParentPath(catelogId, paths);

    //逆序转换
    Collections.reverse(parentPath);

    return parentPath.toArray(new Long[parentPath.size()]);
  }

  /**
   * 级联更新所有关联的数据
   *
   * @param category
   */
  //字符串需要单引号，否则报错不能找到变量值
//    @CacheEvict(value = "category", key = "'getLevel1Categories'")
    /*@Caching(evict = {
            @CacheEvict(value = "category", key = "'getLevel1Categories'"),
            @CacheEvict(value = "category", key = "'getCatalogJson'")
    })*/
  @CacheEvict(value = "category", allEntries = true)//删除指定分区下所有数据
  @Transactional
  @Override
  public void updateCascade(CategoryEntity category) {
    this.updateById(category);
    categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
  }

  //当前方法的结果需要缓存、缓存中有就不需要调用方法,没有需要调用方法
  //可以建立一个缓存分区
  @Cacheable(value = {"category"}, key = "#root.method.name", sync = true)
  @Override
  public List<CategoryEntity> getLevel1Categories() {
    long l = System.currentTimeMillis();
    List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    System.out.println("消耗时间： " + (System.currentTimeMillis() - l));
    return categoryEntities;
  }

  /**
   * 使用缓存实现
   * <p>
   * 1、空结果缓存            穿透
   * 2、设置过期时间+随机值     雪崩
   * 3、加锁                 击穿
   *
   * @return
   */
  @Override
  public Map<String, List<Catalog2Vo>> getCatalogJsonDbWithSpringCache() {
    //给缓存中放json字符串,拿出的json需要逆转为对象：序列化/反序列化
    //1、加入缓存逻辑，缓存中存的数据是json字符串
    //好处:json跨语言、跨平台兼容
    String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
    if (StringUtils.isEmpty(catalogJSON)) {
      //2、缓存中没有，查询数据库
      Map<String, List<Catalog2Vo>> catalogFromDB = getCatalogJsonDb();
      //3、查到的数据转为json放入缓存
      return catalogFromDB;
    }
    Map<String, List<Catalog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {
    });
    return result;
  }


  /**
   * 从数据库查询并封装分类数据
   * <p>
   * 缓存一致性:缓存数据和数据库中的数据一致性
   * 1、双写模式
   * 2、
   * <p>
   * 在此加锁
   *
   * @return
   */
  public Map<String, List<Catalog2Vo>> getCatalogJsonDb() {
    //TODO 本地锁：synchronized、JUC等，只能锁住当前进程；分布式下需要分布式锁
    //synchronized (this){
    //分布式锁实现
    //即setNX,占位
    //Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", "111");
    //原子性操作
//        String uuid = UUID.randomUUID().toString();
//        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid,300,TimeUnit.SECONDS);
    //加锁成功
//        if (lock){
    //redissonClient实现分布式锁
    //1、占分布式锁、去redis占坑
    //锁名字。锁的粒度，越细越快
    RLock lock = redisson.getLock("CatalogJson-lock");
    lock.lock();//加锁
    //如果判断为真一进来就发生中断，也会死锁，因此一整段需要原子性操作才行，
    //getDataFromDB失败会导致死锁，需要设置过期时间
//            stringRedisTemplate.expire("lock",30,TimeUnit.SECONDS);
    Map<String, List<Catalog2Vo>> dataFromDB;
    try {
      dataFromDB = getDataFromDB();
    } finally {
      //解锁,直接删除
      //stringRedisTemplate.delete("lock");
      //获取值+对比删除应该为原子操作，使用lua脚本完成
      //TODO 脚本可以提取到外部
//            String script = "if redis.call('get',KEYS[1] == ARVG[1]) then return redis.call('del',KEYS[1]) else return 0 end";
      //调用该脚本，传入参数
//            Long lock1 = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
//                    Arrays.asList("lock"), uuid);
                /*String lockValue = stringRedisTemplate.opsForValue().get("lock");
                if(uuid.equals(lockValue)){
                    //删除自己的锁
                    stringRedisTemplate.delete("lock");
                }*/
      //分布式解锁
      lock.unlock();
    }
    return dataFromDB;
        /*}
        //加锁失败:重试
        else {
            return getCatalogJsonDb();//自旋进行
        }*/
//        }
  }

  private Map<String, List<Catalog2Vo>> getDataFromDB() {
    //得到锁之后，应该再去缓存中确定异常，没有就继续查询
    String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
    if (!StringUtils.isEmpty(catalogJSON)) {
      //缓存不为空，直接返回
      Map<String, List<Catalog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {
      });
      return result;
    }
    //先查出所有
    List<CategoryEntity> selectList = baseMapper.selectList(null);
    //查出所有一级分类
    List<CategoryEntity> level1Categories = getLevel1Categories();
    //封装数据
    Map<String, List<Catalog2Vo>> catalog1Vos = level1Categories.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
      //1、每个一级分类，查到二级分类
      List<CategoryEntity> categoryEntities = getParentCid(selectList, v.getCatId());
      //封装上面的结果
      List<Catalog2Vo> catalog2Vos = null;
      if (categoryEntities != null) {
        catalog2Vos = categoryEntities.stream().map(l2 -> {
          Catalog2Vo catalog2Vo = new Catalog2Vo(l2.getCatId().toString(), v.getCatId().toString(), l2.getName(), null);
          //给二级分类找三级分类封装成vo
          List<CategoryEntity> catalog3Vos = getParentCid(selectList, l2.getCatId());
          if (catalog3Vos != null) {
            List<Catalog2Vo.Catalog3Vo> collect = catalog3Vos.stream().map(l3 -> {
              //封装成指定格式
              Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
              return catalog3Vo;
            }).collect(Collectors.toList());
            //封装
            catalog2Vo.setCatalog3List(collect);
          }
          return catalog2Vo;
        }).collect(Collectors.toList());
      }
      return catalog2Vos;
    }));
    String s = JSON.toJSONString(catalog1Vos);
    stringRedisTemplate.opsForValue().set("catalogJSON", s, 1, TimeUnit.DAYS);
    return catalog1Vos;
  }


  private List<CategoryEntity> getParentCid(List<CategoryEntity> selectList, Long parentCid) {
    List<CategoryEntity> collect = selectList.stream().filter(item -> Objects.equals(item.getParentCid(), parentCid)).collect(Collectors.toList());
    return collect;
  }

  //TODO 这种业务递归还需要理解
  private List<Long> findParentPath(Long catelogId, List<Long> paths) {
    //收集当前节点id
    paths.add(catelogId);
    CategoryEntity byId = getById(catelogId);
    if (byId.getParentCid() != 0) {
      findParentPath(byId.getParentCid(), paths);
    }
    return paths;
  }

  //递归查找所有菜单的子菜单
  private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
    List<CategoryEntity> children = all.stream().filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId())).map(categoryEntity -> {
      //找到子菜单,递归
      categoryEntity.setChildren(getChildrens(categoryEntity, all));
      return categoryEntity;
    }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());
    return children;
  }
}
